import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score

# 定义CSV文件的本地文件路径
file_path = "D:\\qie.csv"
# 从本地文件读取CSV数据到DataFrame
df = pd.read_csv(file_path)

# 打印数据集的列名
print("列名：", df.columns)

# 检查是否存在 'Species' 列
if 'Species' not in df.columns:
    print("数据集中不存在 'Species' 列")
else:
    # 打印数据集的前五行
    print(df.head())

    # 可视化物种的分布
    sns.countplot(x='Species', data=df)
    plt.title('Distribution of Species')
    plt.show()

    # 可视化FlipperLength, CulmenLength和CulmenDepth的分布
    sns.boxplot(data=df, x='Species', y='FlipperLength')
    plt.title('Boxplot of Flipper Length by Species')
    plt.show()
    sns.boxplot(data=df, x='Species', y='CulmenLength')
    plt.title('Boxplot of Culmen Length by Species')
    plt.show()
    sns.boxplot(data=df, x='Species', y='CulmenDepth')
    plt.title('Boxplot of Culmen Depth by Species')
    plt.show()

    # 显示缺失值的行
    print(df[df.isnull().any(axis=1)])

    # 删除缺失值的行
    df = df.dropna()

    # 准备训练数据
    features = df[['CulmenLength', 'CulmenDepth', 'FlipperLength']]
    labels = df['Species']

    # 将数据集分割为训练集和测试集，测试集占30%
    X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=0.3, random_state=42)

    # 训练逻辑回归模型
    model = LogisticRegression(multi_class='multinomial', solver='lbfgs')
    model.fit(X_train, y_train)

    # 评估模型
    y_pred = model.predict(X_test)
    accuracy = accuracy_score(y_test, y_pred)
    print(f'Model Accuracy: {accuracy:.2f}')
